<?php


namespace app\base\service;

use think\admin\service\AdminService;

use think\Cache;

/**
 * Minimax音频生成服务
 * Class AdminService
 * @package think\admin\service
 */
class MinimaxService extends AdminService
{

    protected $authorization = '';
    protected $group_id = "";
    protected $url = 'https://api.minimaxi.chat/';

    protected function getAuthorization($user_id)
    {
        $api_config_type = $this->app->db->name("ai_user")->where(['id'=>$user_id])->value("api_config_type");
        if($api_config_type==1){
            $user_id=10000;
        }
        $data = $this->app->db->name('ai_api_config')
            ->where(['user_id' => $user_id,'type'=>6])->find();
      //  dump($data);
        if(empty($data)){
            return $this->resulet(0,'请先配置Minimax参数');
        }else{
            $this->authorization = $data['access_key'];
            $this->group_id = $data['appid'];
        }
    }

    protected function resulet($code=0,$msg='',$data=[])
    {
        return [
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ];
    }



    public function createVoiceFile($user_id,$text="",$voice_id='',$model="",$emotion="",$id=0)
    {
        if(empty($voice_id)){
            $voice_id = 'Wise_Woman';
        }
        if(empty($model)){
            $model = "speech-02-hd";
        }
        if(empty($voice_id)){
            $voice_id = 'Wise_Woman';
        }
        if(empty($model)){
            $model = "speech-02-hd";
        }

        $this->getAuthorization($user_id);
        $voice_setting = [
            'voice_id'=>$voice_id
        ];
        $arr = [
            "高兴"=>"happy",
            "悲伤"=>"sad",
            "愤怒"=>"angry",
            "恐惧"=>"fearful",
            "厌恶"=>"disgusted",
            "惊讶"=>"surprised",
            "中性"=>"neutral"
        ];
        if(!$emotion && isset($arr[$emotion])){
            $voice_setting['emotion'] = $arr[$emotion];
        }

        $this->getAuthorization($user_id);
        $url = $this->url."v1/t2a_v2?GroupId={$this->group_id}";
        $data = [
            "model"=>$model,
            "text"=>$text,
            "voice_setting"=>$voice_setting,
            "audio_setting"=>[
                "audio_sample_rate"=>32000,
                "bitrate"=> 128000,
                "format"=>"mp3",
                "channel"=>2
            ]
        ];

        $options['headers'] = ['Authorization:Bearer '.$this->authorization,'Content-Type: application/json'];
        $options['timeout'] = 180;
        $res = http_post($url,json_encode($data),$options);
        $res = json_decode($res,true);
        if($res){
            if(isset($res['data']['audio']) && $res['data']['audio']!=0 && !empty($res['data']['audio'])){
                // 步骤1：清理非十六进制字符
                $cleanedHex = preg_replace('/[^0-9a-fA-F]/', '', $res['data']['audio']);
                if (strlen($cleanedHex) % 2 !== 0) {
                    return $this->resulet(0,"返回数据不是十六进制字符");
                }
                $binaryData = hex2bin($cleanedHex);
                if ($binaryData === false) {
                    return $this->resulet(0,"转换失败，请检查十六进制字符串是否有效");
                }
                file_put_contents($this->app->getRootPath()."public/mp3/{$id}.mp3", $binaryData);
                return $this->resulet(1,'success',"http://dev.blueant.pro/mp3/{$id}.mp3");
            }else{
                return $this->resulet(0,$res['base_resp']['status_msg']);
            }
        }else{
            return $this->resulet(0,'请求失败');
        }
    }


    //音频生成
    public function createVoice($user_id,$text="",$voice_id='',$model="",$emotion="")
    {
        if(empty($voice_id)){
            $voice_id = 'Wise_Woman';
        }
        if(empty($model)){
            $model = "speech-02-hd";
        }

        $this->getAuthorization($user_id);
        $voice_setting = [
            'voice_id'=>$voice_id
        ];
        $arr = [
            "高兴"=>"happy",
            "悲伤"=>"sad",
            "愤怒"=>"angry",
            "恐惧"=>"fearful",
            "厌恶"=>"disgusted",
            "惊讶"=>"surprised",
            "中性"=>"neutral"
        ];
        if(!$emotion && isset($arr[$emotion])){
            $voice_setting['emotion'] = $arr[$emotion];
        }
        $url = $this->url."v1/t2a_async_v2?GroupId={$this->group_id}";
        $data = [
            "model"=>$model,
            "text"=>$text,
            "voice_setting"=>$voice_setting,
            "audio_setting"=>[
                "audio_sample_rate"=>32000,
                "bitrate"=> 128000,
                "format"=>"mp3",
                "channel"=>2
            ]
        ];

        $options['headers'] = ['Authorization:Bearer '.$this->authorization,'Content-Type: application/json'];
        $res = http_post($url,json_encode($data),$options);
        $res = json_decode($res,true);
        if($res){
            if(isset($res['file_id']) && $res['file_id']!=0){
                return $this->resulet(1,'success',$res['file_id']);
            }else{
                return $this->resulet(0,$res['base_resp']['status_msg']);
            }
        }else{
            return $this->resulet(0,'请求失败');
        }


    }

    //音频状态查询
    public function getVoiceStatus($user_id,$task_id)
    {
        $this->getAuthorization($user_id);
        $url = "https://api.minimaxi.chat/v1/query/t2a_async_query_v2?GroupId={$this->group_id}&task_id={$task_id}";
        $options['headers'] = ['Authorization:Bearer '.$this->authorization,'Content-Type: application/json'];
        $res = http_get($url,null,$options);
        $res = json_decode($res,true);
        return $res;
    }

    //获取音频
    public function getVoice($user_id,$file_id)
    {
        $this->getAuthorization($user_id);
        $url = "https://api.minimaxi.chat/v1/files/retrieve?GroupId={$this->group_id}&file_id={$file_id}";
        $options['headers'] = ['Authorization:Bearer '.$this->authorization,'Content-Type: application/json'];
        $res = http_get($url,null,$options);
        $res = json_decode($res,true);
        if($res){
            if(isset($res['file']['download_url']) && $res['file']['download_url']!=0 && !empty($res['file']['download_url'])){
                return $this->resulet(1,'success',$res['file']['download_url']);
            }else{
                return $this->resulet(0,$res['base_resp']['status_msg']);
            }
        }else{
            return  $this->resulet(0,'请求失败');
        }
    }

    //上传文件
    public function uploadFile($user_id,$file_url="")
    {
        $this->getAuthorization($user_id);
       // $file_url = $this->app->getRootPath()."/public/mp3/0.mp3";
        if (!file_exists($file_url)) {
            return $this->resulet(0,'文件不存在');
        }
        //读取二进制文件
      //  $file = file_get_contents($file_url);
        $url = $this->url."v1/files/upload?GroupId={$this->group_id}";
        $options['headers'] = ['Authorization:Bearer '.$this->authorization];
        $options['timeout'] = 180;
        $data = [
            'purpose'=>"voice_clone",
            'file'=> new \CURLFile($file_url)
        ];
        $res = http_post($url,$data,$options);
        $res = json_decode($res,true);
        if($res){
            if(isset($res['base_resp'])&& $res['base_resp']['status_code']==0){
                return $this->resulet(1,'success',$res['file']['file_id']);
            }else{
                return $this->resulet(0,$res['base_resp']['status_msg']);
            }

        }else{
            return $this->resulet(0,'请求失败');
        }
    }

    //声音克隆
    public function voiceClone($user_id,$file_id,$voice_id="")
    {
        $this->getAuthorization($user_id);
        $url = $this->url."v1/voice_clone?GroupId={$this->group_id}";
        $data = [
            "file_id"=>$file_id,
            "voice_id"=>$voice_id
        ];
        $options['headers'] = ['Authorization:Bearer '.$this->authorization,'Content-Type: application/json'];
        $res = http_post($url,json_encode($data),$options);
        $res = json_decode($res,true);
        $options['timeout'] = 180;
        //dump($res);
        if($res){
            if(isset($res['base_resp'])&& $res['base_resp']['status_code']==0){
                return $this->resulet(1,'success',"操作成功");
            }else{
                return $this->resulet(0,$res['base_resp']['status_msg']);
            }
        }else{
            return $this->resulet(0,'请求失败');
        }

    }



}
